<template>
    <div>
        <div class="m-alert"  style="width: 45%">
            <div>
                <div>提示：</div>
                <div>1、文本、图片、外链图文、小程序都将占用1次机会（若文本为空将不占用），每个客户每月只可收到4次企业群发；</div>
                <div>2、如客户本月已收到4次群发消息本条邀请将不会成功发送。</div>
            </div>
        </div>
        <el-form :model="ruleForm" ref="ruleForm" label-width="100px" class="demo-ruleForm"  style="width: 45%">
            <el-form-item label="群发对象" prop="member">
                <el-row>
                    <el-col>
                        <el-radio label="1" v-model="ruleForm.member">全部客户群</el-radio>
                        <el-radio label="2" v-model="ruleForm.member">筛选客户群</el-radio>
                    </el-col>
                    <el-col>
                        <el-button v-if="ruleForm.member == '2'" size="small" @click="addClientGroup">+ 添加群聊
                        </el-button>
                        <el-tag v-for="tag in members" :key="tag.clientGroupName" closable
                                @close="closeTagHandle(tag)"
                                style="margin-right: 10px"> {{ tag.clientGroupName }}
                        </el-tag>
                        已选择{{members.length}}个群聊
                    </el-col>
                </el-row>
            </el-form-item>
            <el-form-item label="群发内容" prop="desc">
                <el-input type="textarea" v-model="ruleForm.groupMessage" style="width: 70%"
                          placeholder="请输入内容"></el-input>
            </el-form-item>
            <el-form-item label="上传素材附件">
                <MaterialContentText ref="contentText" :contentType="[2]" :imageList="imageList"/>
            </el-form-item>
            <el-form-item label="群发时间" prop="times">
                <el-radio label="1" v-model="ruleForm.time">立即发送</el-radio>
                <el-radio label="2" v-model="ruleForm.time">定时发送</el-radio>
                <el-date-picker
                    v-if="ruleForm.time == '2'"
                    v-model="ruleForm.sendTime"
                    type="datetime"
                    placeholder="选择时间">
                </el-date-picker>
            </el-form-item>
            <el-form-item>
                <el-button type="primary" @click="back">返回</el-button>
                <el-button type="primary" @click="saveMessage">通知员工发送</el-button>
                &nbsp;&nbsp;通知成员，向选中客户群发送以上消息
            </el-form-item>
        </el-form>

        <el-dialog title="选择群聊" :visible.sync="group" width="30%" :close-on-click-modal="false">
            <div style="padding: 0px 0px 0px 30px;">
                <MultipleSelect ref="selectMultipleMember" :listFields="listGroupFields" :dataSource="listGroup"
                                type="filter"/>
                <div class="button-center" style="padding: 10px 10px;">
                    <el-button size="mini" @click="close">取消</el-button>
                    <el-button size="mini" type="primary" @click="getGroupHandle()">确定</el-button>
                </div>
            </div>
        </el-dialog>
    </div>
</template>

<script>
    import MultipleSelect from "@/components/list_multiple_select/list_multiple_select"
    import MaterialContentText from "@/components/material_content_text/material_content_text"
    import ElementUI from 'element-ui'

    // 修改 el-dialog 默认点击遮照为不关闭
    ElementUI.Dialog.props.closeOnClickModal.default = false;
    export default {
        name: "save",
        components: {
            MultipleSelect, MaterialContentText
        },
        data() {
            return {
                group: false,
                ruleForm: {
                    member: '1',
                    resource: [],
                    desc: '',
                    time: '',
                    times: '',
                },
                resource: [{"key": 1, "label": "群聊1", "disabled": false},
                    {"key": 2, "label": "群聊2", "disabled": false}, {"key": 3, "label": "群聊3", "disabled": false},
                    {"key": 4, "label": "群聊4", "disabled": false}],
                resourceArr: [],


                listGroupFields: {
                    clientGroupName: '群聊名称',
                    empName: '群主名称'
                },
                listGroup: [],
                clientGroup: {},
                members: [],
                fileList: [],

                imageList: [],
                //**
            }
        },
        methods: {
            handleClose(item) {
                this.ruleForm.resource.splice(this.ruleForm.resource.indexOf(item), 1);
            },
            add() {
                this.group = true
            },
            back() {
                this.$emit("currentHandler", "list")
            },

            getData(data) {
                this.clientGroup = data
                this.group = false

            },

            addClientGroup() {
                let that = this
                that.title = '添加群聊'
                that.$request("/api/custGroup/selectGroup/1_0", "", "POST").then((data) => {
                    that.listGroup = [...data.rows]
                    that.group = true
                })
            },
            //**
            quxiao() {
                this.group = false
            },
            leftChange(e) {
                let value = this.resourceArr
                let a = value.concat(e);
                this.resourceArr = a
            },
            rightChange(e) {
                let value = []
                this.resourceArr.map((item) => {
                    if (item != e[0]) {
                        value.push(item)
                    }
                })
                this.resourceArr = value;
            },
            //提交
            peoples() {
                let arr = this.resourceArr
                let resource = this.resource
                let result = []
                arr.map((value, index, array) => {
                    resource.map((item) => {
                        if (item.key == value) {
                            result.push(item)
                        }
                    })
                })
                this.ruleForm.resource = result
                this.quxiao()
            },
            close() {
            },
            closeTagHandle(tag) {
                this.ruleForm.members.splice(this.ruleForm.members.indexOf(tag), 1);
            },
            getGroupHandle() {
                let data = this.$refs.selectMultipleMember.getData();
                this.group = false
                this.members = data
            },
            handleRemove() {

            },
            beforeRemove() {

            },
            handleExceed() {

            },
            handlePreview() {
            },

            async saveMessage() {
                let that = this;
                let formData = this.ruleForm;

                if (formData.groupMessage == null || formData.groupMessage == "") {
                    that.$message.error("请输入群发内容")
                    return
                }

                let chooseTime = that.$moment(formData.sendTime).valueOf() / 1000;
                let nowTime = that.$moment().unix()

                if (chooseTime <= nowTime) {
                    that.$message.error("不能选择以前的时间")
                    return
                }

                let groupRes = await that.$request("/api/custGroup/selectGroup/1_0", "", "POST");
                let groupIdList = []
                let groupList = groupRes.rows;

                if (formData.member != '1') {
                    groupList = that.members
                }

                groupList.map((item) => {
                    groupIdList.push(item.clientGroupId)

                })

                let groupId = groupIdList.toString()

                this.ruleForm['groupId'] = groupId
                this.ruleForm.groupSendType = '1';
                this.ruleForm.sendStatus = '未发送'
                if (this.ruleForm.time == '1') {
                    that.ruleForm.sendTime = null
                }
                if (that.ruleForm.time == '1') {
                    this.ruleForm['alertTime'] = ""
                } else {
                    this.ruleForm['alertTime'] = chooseTime
                }
                this.ruleForm.imageList = that.$refs.contentText.getData()
                this.$request("/api/groupMessage/addGroupMessage/1_0", this.ruleForm, "POST").then((data) => {
                    if (data.data == 1) {
                        this.$message({
                            message: "操作成功 ！",
                            type: 'success'
                        });
                    }
                    this.ruleForm = {}
                })
                for (let i in groupList) {
                    let key = groupList[i]
                    let mission = {
                        missionName: "客户群群发任务",
                        missionStatus: "创建",
                        sendType: "2",
                        sendEmpId: key.empId,
                        taskCorrelationType: "9",
                        missionInfoType: '1',
                        missionMessage: that.ruleForm.groupMessage,
                        clientGroupId: key.clientGroupId,
                        imageList: that.$refs.contentText.getData()
                    }
                    await this.$request("/api/task/addTask/1_0", mission, "POST")
                }

                that.$refs.contentText.getData()
                this.back()
            },

            handleAvatarChangeImg1(file) {
                if (this.beforeAvatarUpload(file.raw)) {
                    this.wordsForm.unlimitedLogo = URL.createObjectURL(file.raw);
                    this.wordsForm.type = 2;
                }
            },
        }
    }
</script>

<style scoped>
    .el-icon-info {
        color: #35abff;
        margin-right: 10px;
    }
</style>
